package com.jy.project.service.imp;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.format.DatePrinter;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.jy.project.constant.MaterialConstant;
import com.jy.project.controller.ApplyController;
import com.jy.project.controller.MatericalController;
import com.jy.project.domain.*;
import com.jy.project.dto.*;
import com.jy.project.enums.ApplyTypeEnum;
import com.jy.project.enums.ApplyTypeMatericalEnum;
import com.jy.project.enums.QualityStatusEnum;
import com.jy.project.ex.BizException;
import com.jy.project.mapper.*;
import com.jy.project.service.ApplyService;
import com.jy.project.service.MaterialService;
import com.jy.project.service.imp.defult.DefaultApplyBusinessImp;
import com.jy.project.util.*;
import com.jy.project.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.*;

@Service("applyCollectServiceImpl")
@Slf4j
public class ApplyCollectServiceImpl extends DefaultApplyBusinessImp implements ApplyService {


    @Autowired
    private ApplyMapper applyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private ApplyCollectMapper applyCollectMapper;

    @Autowired
    private ApplyBorrowMapper applyBorrowMapper;

    @Autowired
    private ApplyReturnMapper applyReturnMapper;

    @Autowired
    private ApplyRenewMapper  applyRenewMapper;

    @Autowired
    private ApplyStockReturnMapper  applyStockReturnMapper;


    @Autowired
    private ApplyHandoverMapper  applyHandoverMapper;


    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;


    @Autowired
    TransactionDefinition transactionDefinition;



    public boolean insertApply(ApplyDTO dto) {

        if (dto.getUseUserId() == null || dto.getUseUserId() == 0) {
            throw new BizException("使用人必须填写");
        }
        dto.setApplyType(ApplyTypeEnum.COLLECT.getCode());
        Set<Integer> set = new HashSet<>();
        set.add(dto.getApplyType());
        dto.setExt(JSONObject.toJSONString(set));
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            boolean bl = this.insertApplyBusiness(dto);
            if (bl == false) {
                throw new BizException("申请领取失败");
            }
        }catch (Exception e){
            dataSourceTransactionManager.rollback(transactionStatus);
            throw  e;
        }
        dataSourceTransactionManager.commit(transactionStatus);
        return true;
    }

    @Override
    public List<ApplyQualitVO> listApplyQualityVO(ApplyQueryDTO dto) {

        return applyMapper.listApplyyQualityVO(dto);
    }

    @Override
    public List<ApplyDeptAdminVO> listDeptAdminApplyVO(ApplyDeptAdminQueryDTO dto) {
        PageHelper.startPage(dto);
        return applyMapper.listDeptAdminApplyVO(dto);
    }

    @Override
    public boolean applyAdopt(ApplyAdoptDTO dto) {
        log.info("审批通过领取单");
        String applyNo = dto.getApplyNo();
        Apply apply = applyMapper.getApplyByApplyNo(applyNo);
        if (apply==null){
            throw  new BizException("申请单不存在");
        }

        Example example =new Example(ApplyCollect.class);
        example.createCriteria().andEqualTo("applyNo",applyNo);
        List<ApplyCollect> applyCollects = applyCollectMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(applyCollects)){
            throw  new BizException("数据不存在");
        }
        List<String> materialNos=new ArrayList<>();
        for (int i = 0; i < applyCollects.size(); i++) {
            materialNos.add(applyCollects.get(i).getMaterialNo());
        }

        ApplyUpdateDTO applyUpdateCollectDTO=new ApplyUpdateDTO();
        BeanUtils.copyProperties(apply,applyUpdateCollectDTO);
        String s = CommonStringUtils.toStr(materialNos);
        List<MaterialVO> materialVOS = materialMapper.listMaterialVOByMaterialNos(s);
        if (materialVOS.isEmpty()){
            throw  new BizException("数据不存在");
        }
        for (MaterialVO materialVO : materialVOS) {
            Integer useStatus = materialVO.getUseStatus();
            if (useStatus.equals("1")){
                throw  new BizException("当前物资已经在使用状态");
            }
        }
        applyUpdateCollectDTO.setMaterialNos(s);
        applyUpdateCollectDTO.setUseStatus(1);
        return materialMapper.updateApplyUpdateCollectDTO(applyUpdateCollectDTO)>0;
    }

    @Override
    public boolean applyReject(ApplyAdoptDTO dto) {
        log.info("驳回通过领取单");
        return true;
    }

    @Override
    public ServiceResultUtils listMaterialDetailsVO(MaterialDetailsDTO dto) {
        String applyNo = dto.getApplyNo();
        if (StringUtils.isEmpty(applyNo)){
            throw new BizException("applyNo不能为空");
        }
        Apply applyByApplyNo = applyMapper.getApplyByApplyNo(applyNo);
        if (applyByApplyNo==null){
            throw new BizException("Apply不能为空");
        }
        Integer applyType = applyByApplyNo.getApplyType();

        // 参考 ApplyTypeEnum
        switch (applyType){
            case 20:
                List<Apply> collectList= applyCollectMapper.listMaterialDetailsVO(dto);
               return ServiceResultUtils.success(collectList);
            case 30:
                List<Apply> stockReturnList = applyStockReturnMapper.listMaterialDetailsVO(dto);
                return ServiceResultUtils.success(stockReturnList);
            case 40:
                List<MaterialDetailsVO>   materialDetailsVOS= applyBorrowMapper.listMaterialDetailsVO(dto);
                return ServiceResultUtils.success(materialDetailsVOS);
            case 50:
                List<Apply> renewList= applyRenewMapper.listMaterialDetailsVO(dto);
                return ServiceResultUtils.success(renewList);
            case 60:
                List<Apply> returnList= applyReturnMapper.listMaterialDetailsVO(dto);
                return ServiceResultUtils.success(returnList);
            case 70:
                List<Apply> insertList = applyMapper.listApply(applyNo);
                return ServiceResultUtils.success(insertList);
            case 80:
                List<MaterialHandoverDetailsVO>  handoverList= applyHandoverMapper.listMaterialDetailsVO(dto);
                return ServiceResultUtils.success(handoverList);
        }
            return ServiceResultUtils.success(null);

    }

    @Override
    public List<ApplyUserVO> listUserApplyVO(ApplyUserQueryDTO dto) {
        return null;
    }

    @Override
    public boolean insertApplyBusiness(ApplyDTO dto) {
        if (dto==null){
            throw new BizException("Apply对象为空");
        }
        //检查物资单号
        checkApplyNo(dto.getApplyNo());
        Long id = dto.getUserId();
        User user = userMapper.selectByPrimaryKey(id);
        if (user==null){
            throw  new BizException("用户信息可能找不到");
        }
        String[] checkMaterialNos = dto.getCheckMaterialNos();
        if (checkMaterialNos==null){
            throw  new BizException("没有选中信息");
        }
        if (checkMaterialNos.length<0){
            throw  new BizException("没有选中信息");
        }
        List<MaterialVO> materialVOS = checkMaterialNos(checkMaterialNos);
        if (materialVOS.isEmpty()){
            throw  new BizException("当前编号资产找不到,或为无法使用状态");
        }
        //使用人
        User useUser =null;
        if (dto.getUseUserId()!=null&&dto.getUseUserId()!=0){
            useUser= userMapper.selectByPrimaryKey(dto.getUseUserId());
            if (useUser==null){
                throw  new BizException("使用者用户信息找不到");
            }
        }

        for (int i = 0; i < materialVOS.size(); i++) {

            Apply ay = this.create();
            ay.setApplyType(dto.getApplyType());
            ay.setName(ApplyTypeEnum.getValue(ay.getApplyType()));
            ay.setApplicantCompanyNo(user.getCompanyNo());
            ay.setApplicantCompanyName(user.getCompanyName());
            ay.setApplicantDeptNo(user.getDeptNo());
            ay.setApplicantDeptName(user.getDeptName());
            ay.setApplicantUserId(user.getId());
            ay.setApplicantUserNickName(user.getNickName());

            if (useUser!=null){
                ay.setUseCompanyNo(useUser.getCompanyNo());
                ay.setUseCompanyName(useUser.getCompanyName());
                ay.setUseDeptNo(useUser.getDeptNo());
                ay.setUseDeptName(useUser.getDeptName());
                ay.setUseUserId(useUser.getId());
                ay.setUseNickName(useUser.getNickName());
            }
            ay.setExt(dto.getExt());
            ay.setRemarks(dto.getRemarks());
            MaterialVO materialVO = materialVOS.get(i);
            ay.setPlanningType(materialVO.getPlanningType());
            ApplyCollect applyCollect=new ApplyCollect();
            BeanUtils.copyProperties(ay,applyCollect);
            String materialNo = materialVO.getMaterialNo();
            applyCollect.setMaterialNo(materialNo);
            String name = materialVO.getName();
            applyCollect.setMaterialName(name);
            ay.setMaterialNo(materialNo);
            ay.setMaterialName(name);
            Long managementUserId = materialVO.getManagementUserId();
            ay.setManagementUserId(managementUserId);
            applyCollect.setStatus(0);
            applyCollect.setImg(materialVO.getImg());
            applyCollectMapper.insert(applyCollect);
            ay.setStatus(0);
            applyMapper.insertSelective(ay);

        }
        return  true;
    }

    @Override
    public Apply create() {
        Apply apply = new Apply();
        apply.setApplyNo(CodeUtils.generateApplyNo(ApplyTypeMatericalEnum.COLLECT.getValue()));
        Date date = new Date();
        apply.setCreateAt(date);
        apply.setUpdateAt(date);
        apply.setUpdateDay(date);
        apply.setIsDelete(0);
        return  apply;

    }

    private  List<MaterialVO> checkMaterialNos(String[] split ){
        String s = CommonStringUtils.toStr(split);
        List<MaterialVO> materialVOS = materialMapper.listMaterialVOByMaterialNos(s);
  
        for (int i = 0; i < materialVOS.size(); i++) {
            MaterialVO materialVO = materialVOS.get(i);
            String materialNo = materialVO.getMaterialNo();
            Apply applyByMaterialNo = applyMapper.getApplyByMaterialNo(materialNo);
            if (applyByMaterialNo!=null){
                throw  new BizException("当前"+materialVO.getMaterialNo()+"资产被人申请占用中");
            }
            if (materialVO.getUseStatus()!=0){
                throw  new BizException("当前"+materialVO.getMaterialNo()+"资产不是闲置状态");
            }
            String[] qualityStatus = materialVO.getQualityStatus();
            if (qualityStatus!=null ||qualityStatus.length>0){
                boolean bl=false;
                for (int j = 0; j < qualityStatus.length; j++) {
                    String qStatus = qualityStatus[j];
                    if (qStatus.equals(QualityStatusEnum.COLLECT_ABLE.getCode().toString())){
                        bl=true;
                    }
                }
                if (bl==false){
                    throw  new BizException("编号"+materialVO.getMaterialNo()+"资产质量状态设置不可领取");
                }
            }

        }
        return  materialVOS;
    }
}
